﻿//#define ADAPT_DEBUG
//#define ADRE_DEBUG
//#define SYSTEM1_DEBUG
//#define STANDARDIZED

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace GE_Database_Manager
{
	public partial class MainForm : Form
	{
		private List<Database> databases;
		private System.Data.SqlClient.SqlConnection standrizedDbConnection = null;
		private System.Data.SqlClient.SqlConnection exportConnection = null;
        private BackgroundWorker worker;
        private delegate void updateDelagate(int value, string text);
        private int progressStep;

		public MainForm()
		{
			InitializeComponent();

			// Initialize list of databases
			databases = new List<Database>();

			// Set the Authentication method to Integrated Security by default
			comboBox_Authentication.SelectedIndex = 0;
			dropDown_Export_Auth.SelectedIndex = 0;

            // progress bar background worker, with necessary dependencies..
            worker = new BackgroundWorker();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.WorkerReportsProgress = true;
            worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
            worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_complete);
            progressBar.MarqueeAnimationSpeed = 0;
           
            
			// Initialize the Database Tree
			tree_Selected.Nodes.Add("System1", "System1");
			tree_Selected.Nodes.Add("ADRE", "ADRE");
			tree_Selected.Nodes.Add("ADAPT", "ADAPT");
			tree_Selected.Nodes.Add("Standardized", "Standardized");


			// Initialize the Export Screen
			dd_c_comm.SelectedIndex = 0;
			dd_c_cond.SelectedIndex = 0;
			dd_c_end.SelectedIndex = 0;
			dd_c_id.SelectedIndex = 0;
			dd_c_source.SelectedIndex = 0;
			dd_c_start.SelectedIndex = 0;
			dd_d_id.SelectedIndex = 0;
			dd_d_name.SelectedIndex = 0;
			dd_e_abbrev.SelectedIndex = 0;
			dd_e_id.SelectedIndex = 0;
			dd_e_mult.SelectedIndex = 0;
			dd_e_name.SelectedIndex = 0;
			dd_e_offset.SelectedIndex = 0;
			dd_m_id.SelectedIndex = 0;
			dd_m_make.SelectedIndex = 0;
			dd_m_serial.SelectedIndex = 0;
			dd_m_site.SelectedIndex = 0;
			dd_m_tag.SelectedIndex = 0;
			dd_m_type.SelectedIndex = 0;
			dd_m_workorder.SelectedIndex = 0;
			dd_sens_id.SelectedIndex = 0;
			dd_sens_mid.SelectedIndex = 0;
			dd_sens_name.SelectedIndex = 0;
			dd_stage_desig.SelectedIndex = 0;
			dd_stage_fixed.SelectedIndex = 0;
			dd_stage_gear.SelectedIndex = 0;
			dd_stage_id.SelectedIndex = 0;
			dd_stage_mid.SelectedIndex = 0;
			dd_stage_pcount.SelectedIndex = 0;
			dd_stage_pinion.SelectedIndex = 0;
			dd_stage_planet.SelectedIndex = 0;
			dd_stage_ring.SelectedIndex = 0;
			dd_stage_sun.SelectedIndex = 0;
			dd_w_bitsper.SelectedIndex = 0;
			dd_w_date.SelectedIndex = 0;
			dd_w_engrid.SelectedIndex = 0;
			dd_w_id.SelectedIndex = 0;
			dd_w_srate.SelectedIndex = 0;
			dd_w_rpm.SelectedIndex = 0;
			dd_w_status.SelectedIndex = 0;

            #region DEBUGGING STUFF
                #if (ADAPT_DEBUG)
                    populateAdaptDatabase();
                #endif

                #if(SYSTEM1_DEBUG)
                    populateSystem1Database();
                #endif

                #if(ADRE_DEBUG)
                    populateAdreDatabase();
                #endif

				#if(STANDARDIZED)
					populateStandadrdizedDatabases();
				#endif
            #endregion
        }

		private void button_System1_Click(object sender, EventArgs e)
		{
			System1_Form s = new System1_Form();
			s.passDatabase = new System1_Form.PassDatabase(PassSystem1);
			s.ShowDialog();
		}

		private void PassSystem1(object sender)
		{
			System1 receivedDb = (System1)sender;
			
			// Add new DB to the databases list
			databases.Add(receivedDb);

			// Check if this System1 database has already been added to the list
			if (tree_Selected.Nodes["System1"].Nodes.ContainsKey(receivedDb.Key))
			{
				MessageBox.Show("Database Already added...");
			}
			else
			{
				// Add new DB to the tree
				tree_Selected.Nodes["System1"].Nodes.Add(receivedDb.Key, "Database");
				tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Configuration Database: " + receivedDb.ConfigurationDatabaseName);
				tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Historical Database: " + receivedDb.HistoricalDatabaseName);
				tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Malfunction Tags: " + receivedDb.MalfunctionTagFilepath);
				tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Comments:  " + receivedDb.CommentsFilePath);

				// Expand new nodes
				tree_Selected.Nodes["System1"].Expand();
				tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Expand();
			}
		}

		private void PassStandardized(object sender)
		{
			Standardized receivedDb = (Standardized)sender;

			// Add new DB to the databases list
			databases.Add(receivedDb);

			// Check if this System1 database has already been added to the list
			if (tree_Selected.Nodes["Standardized"].Nodes.ContainsKey(receivedDb.Key))
			{
				MessageBox.Show("Database Already added...");
			}
			else
			{
				// Add new DB to the tree
				tree_Selected.Nodes["Standardized"].Nodes.Add(receivedDb.Key, "Database");
				tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Nodes.Add("Server: " + receivedDb.ServerName);
				tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Nodes.Add("Standardized Database: " + receivedDb.DatabaseName);

				// Expand new nodes
				tree_Selected.Nodes["Standardized"].Expand();
				tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Expand();
			}
		}

		public void PassADAPT(object sender)
		{
			// add the adapt database to the list
			ADAPT receivedDb = (ADAPT)sender;
			databases.Add(receivedDb);

			if (tree_Selected.Nodes["ADAPT"].Nodes.ContainsKey(receivedDb.Key))
			{
				MessageBox.Show("Database Already added...");
			}
			else
			{
				// add database to the tree
				tree_Selected.Nodes["ADAPT"].Nodes.Add(receivedDb.Key, "Database");
				tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("WaveForm Data: " + receivedDb.WavFormData);
				tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("Kinematic Data: " + receivedDb.KinematicData);
				tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("NamePlate Data: " + receivedDb.NamePlateData);
				tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("Malfunction Data : " + receivedDb.MalfunctionData);
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("Data Attributes : " + receivedDb.DataAttributes);

				// expand new nodes
				tree_Selected.Nodes["ADAPT"].Expand();
				tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Expand();
			}
		}

        public void PassADRE(object sender)
        {
            // add ADRE database to list
            ADRE receiveDb = (ADRE)sender;
            databases.Add(receiveDb);

            // if data base hasn't already been added, add it to the tree
            if (tree_Selected.Nodes["ADRE"].Nodes.ContainsKey(receiveDb.Key))
                MessageBox.Show("Database already added...");
            else
            {
                tree_Selected.Nodes["ADRE"].Nodes.Add(receiveDb.Key, "Database");
                tree_Selected.Nodes["ADRE"].Nodes[receiveDb.Key].Nodes.Add("Waveform Data: " + receiveDb.Waveform);
				tree_Selected.Nodes["ADRE"].Nodes[receiveDb.Key].Nodes.Add("Kinematic Data: " + receiveDb.Kinematics);
				tree_Selected.Nodes["ADRE"].Nodes[receiveDb.Key].Nodes.Add("Nameplate Data: " + receiveDb.Nameplate);
				tree_Selected.Nodes["ADRE"].Nodes[receiveDb.Key].Nodes.Add("Malfunction Data: " + receiveDb.Condition);
                tree_Selected.Nodes["ADRE"].Expand();
                tree_Selected.Nodes["ADRE"].Nodes[receiveDb.Key].Expand();
            }

        }

        private void setFont(TextBox targetTextBox, FontStyle newFontStyle, Color newColor)
        {
            targetTextBox.Font = new Font(targetTextBox.Font, newFontStyle);
            targetTextBox.ForeColor = newColor;
        }

        private void button_ADAPT_Click(object sender, EventArgs e)
        {
            ADAPT_Form adapt = new ADAPT_Form();
            adapt.passDatabase = new ADAPT_Form.PassDatabase(PassADAPT);
            adapt.ShowDialog();
        }

        private void button_ADRE_Click(object sender, EventArgs e)
        {
            ADRE_Form adre = new ADRE_Form();
            adre.passDatabase = new ADRE_Form.PassDatabase(PassADRE);
            adre.ShowDialog();
        }

		private void button_Go_Click(object sender, EventArgs e)
        {
            // init the progess bar value
            progressBar.Style = ProgressBarStyle.Marquee;

			// create the wrapper
			String databaseName = (radio_CreateNew.Checked) ? textBox_Database.Text : comboBox_Database.Text;
		    Standardized_Wrapper wrapper = new Standardized_Wrapper(standrizedDbConnection, radio_CreateNew.Checked, databaseName);
            
            // check for sql connection and valid databse names
            if (checkForValidConnection())
            {
                //disable the go button
                button_Go.Enabled = false;

                // start processing in the background..
				worker.RunWorkerAsync(wrapper);
            }    
		}

        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
			Standardized_Wrapper wrapper = (Standardized_Wrapper)e.Argument;

            // calculate progress step
            progressStep = 50;
          
            // start progress bar
            worker.ReportProgress(100, "Loading Database.."); 

            // proccess each database
            foreach (Database db in databases)
            {
                // pass the progress value
                db.passProgress = new Database.PassProgress(worker_ProgressChanged);

                // set the progress step for each database
                db.ProgressStep = progressStep;

                // proccess the database..
                db.Process(wrapper);
            }

            worker.ReportProgress(0, "Complete..");

            //progressBar.MarqueeAnimationSpeed = 0;
   
        }


        private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            // check if another thread called this...
            if (InvokeRequired)
            {
                Invoke(new updateDelagate(updateProgress),e.ProgressPercentage,e.UserState.ToString());
            }
            else
            {
                updateProgress(e.ProgressPercentage, e.UserState.ToString());
            }
        }

        private void updateProgress(int value, string text) 
        {
            if (value == 0)
            {
                progressBar.Style = ProgressBarStyle.Blocks;
                progressBar.MarqueeAnimationSpeed = 0;
                statusLabel.Text = text;
            }
            else 
            {
                progressBar.MarqueeAnimationSpeed = value;
                statusLabel.Text = text;
            }
 
        }

        private void worker_complete(Object sender, RunWorkerCompletedEventArgs e)
        {
            button_Go.Enabled = true;
        }

        private bool checkForValidConnection()
        {
            // check for valid sql server connection
            if (standrizedDbConnection == null)
            {
                MessageBox.Show("Please connect to SQL Server");
                return false;
            }
            // check if the user selected an existing database 
            else if (radio_InsertInto.Checked)
            {
                if (comboBox_Database.SelectedItem == null)
                {
                    MessageBox.Show("Please select a database");
                    return false;
                }
            }
            // check if the user entered correct database name 
            else if (radio_CreateNew.Checked)
            {
                if (textBox_Database.Text == String.Empty)
                {
                    MessageBox.Show("Please Enter a database name");
                    return false;
                }
                else if (textBox_Database.Text.Contains(" "))
                {
                    MessageBox.Show("Database Name Can not contain Spaces..");
                    return false;
                }
				else if (databaseExists(textBox_Database.Text))
				{
					//TODO shorten
					MessageBox.Show("A Database with that name already exists.\r\n" +
						"If you would like to overwrite this database, please drop it manually.\r\n" +
						"If you would like to insert data into this database, please select 'Insert Into Existing Database' option.");
					return false;
				}
            }
                return true;   
        }


		private void comboBox_Authentication_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (comboBox_Authentication.SelectedIndex == 0)
			{
				textBox_Username.Enabled = false;
				textBox_Password.Enabled = false;
				label_Password.Enabled = false;
				label_Username.Enabled = false;
			}
			else
			{
				textBox_Username.Enabled = true;
				textBox_Password.Enabled = true;
				label_Password.Enabled = true;
				label_Username.Enabled = true;
			}
		}

		private bool databaseExists(string givenDbName)
		{
			try
			{
				// Get a list of databases/catalogs
				standrizedDbConnection.Open();
				DataTable tbl_databases = standrizedDbConnection.GetSchema("Databases");
				standrizedDbConnection.Close();

				foreach (DataRow row in tbl_databases.Rows)
				{
					if (row["database_name"].ToString() == givenDbName) return true;
				}
			}
			catch (Exception ex)
			{
                standrizedDbConnection.Close();
				//TODO
				return false;
			}
			return false;
		}

		private void button_Connect_Click(object sender, EventArgs e)
		{
			try
			{
				standrizedDbConnection = new System.Data.SqlClient.SqlConnection();		// SQL Connection

				// Connect to the given server
				if (comboBox_Authentication.SelectedIndex == 0)		// Integrated Security
				{
					standrizedDbConnection.ConnectionString = String.Format("Server={0};Integrated Security=true", textBox_ServerName.Text);
				}
				else	// SQL Server Authentication
				{
					standrizedDbConnection.ConnectionString = String.Format("Server={0};User ID={1};Password={2}",
						textBox_ServerName.Text, textBox_Username.Text, textBox_Password.Text);
				}

				// Get a list of databases/catalogs
				standrizedDbConnection.Open();
				DataTable tbl_databases = standrizedDbConnection.GetSchema("Databases");
				standrizedDbConnection.Close();

				// Populate dropdown menus
				comboBox_Database.Items.Clear();

				foreach (DataRow row in tbl_databases.Rows)
				{
					comboBox_Database.Items.Add(row["database_name"].ToString());
				}

				// Precondition: Connection has been successful
				button_Connect.Enabled = true;
				radio_InsertInto.Enabled = true;
				radio_CreateNew.Enabled = true;
				comboBox_Database.Enabled = true;
				textBox_Database.Enabled = true;
				button_Go.Enabled = true;

				// Alert user to successful connection
				statusLabel.Text = String.Format("Successfully connected to '{0}'", textBox_ServerName.Text);
			}
			catch (Exception ex)
			{
                standrizedDbConnection.Close();
				// Alert user
				MessageBox.Show(String.Format("Unable to connect to server '{0}':\r\n{1}", textBox_ServerName.Text, ex.Message),
					"Connection Unsuccessful!", MessageBoxButtons.OK, MessageBoxIcon.Error);
                standrizedDbConnection = null;
			};
		}

		private void textBox_ServerName_Leave(object sender, EventArgs e)
		{
			
		}

		private void radio_InsertInto_CheckedChanged(object sender, EventArgs e)
		{
			if (radio_InsertInto.Checked)
			{
				comboBox_Database.Enabled = true;
				textBox_Database.Enabled = false;
			}
			else
			{
				comboBox_Database.Enabled = false;
				textBox_Database.Enabled = true;
			}
		}

		private void button_AddStandardizedDB_Click(object sender, EventArgs e)
		{
			Standardized_Form s = new Standardized_Form();
			s.passDatabase = new Standardized_Form.PassDatabase(PassStandardized);
			s.ShowDialog();
        }


        /// <summary>
        ///  displays context menu if user right clicked on database
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tree_Selected_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) 
        {
            // change node selection
            tree_Selected.SelectedNode = e.Node;

            // check for valid node  and  check if right button is clicked on mouse
            if (e.Node.Text == "Database" && e.Button == MouseButtons.Right)
            {
                    // show context menu
                    contextMenuStrip.Show(MousePosition);
                
            }
        }
        /// <summary>
        /// This function removes the selected node from list and tree
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void removeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // grab the selected database based on key
            Database rmDatabase = getDatabase(tree_Selected.SelectedNode.Name);

            // check for valid database
            if (rmDatabase != null)
            {
                // remove from list
                databases.Remove(rmDatabase);

                // remove from GUI
                tree_Selected.SelectedNode.Remove();
            }
        }


        /// <summary>
        /// grabs a database based on the key
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        private Database getDatabase(string key)
        { 
            // get each database
            foreach (var database in databases)
            {
                // return the database if the keys match
                if (database.Key == key)
                {
                    return database;
                }
            }

            return null;
        }

		private void textBox_ServerName_TextChanged(object sender, EventArgs e)
		{
			radio_InsertInto.Enabled = false;
			radio_CreateNew.Enabled = false;
			comboBox_Database.Enabled = false;
			textBox_Database.Enabled = false;
			button_Go.Enabled = false;

			if (textBox_ServerName.Text.Length > 0)
				button_Connect.Enabled = true;
			else
				button_Connect.Enabled = false;
		}


        #region Debugging
        /// <summary>
        /// This function populates an ADAPT database for debbugin purposes
        /// </summary>
        private void populateAdaptDatabase() 
        {
            ADAPT receivedDb = null;

            if (System.Environment.MachineName == "ERICK-PC")
            {
                // add the adapt database to the list
                receivedDb = new ADAPT(
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\CV_A1_Gearbox_Sensor_1_Sync_Waveform_010820131414_100820131414.csv",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\Bosch Rexroth 455 60Hz Ratio=85.604.xlsm",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\90000159 - EnelChisholmView_WTG_A001_MalfunctionTag.txt",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\Nameplate.pdf",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\90000159 - EnelChisholmView_WTG_A001_DataAttributes.txt",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\Comments.txt"
                    );
            }
			else if (System.Environment.MachineName.ToLower() == "pat-laptop")
            {
				receivedDb = new ADAPT(
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\WTG_A001\CV_A1_Gearbox_Sensor_1_Sync_Waveform_010820131414_100820131414.csv",
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\Bosch Rexroth 455 60Hz Ratio=85.604.xlsm",
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001_MalfunctionTag.txt",
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\NamePlate.pdf",
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\90000159 - EnelChisholmView_WTG_J001_DataAttributes.txt",
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\Adapt Data\90000159 - EnelChisholmView_WTG_A001\Comments.txt"
					);
            }
            else 
            {
                return;
            }

            databases.Add(receivedDb);

            if (tree_Selected.Nodes["ADAPT"].Nodes.ContainsKey(receivedDb.Key))
            {
                MessageBox.Show("Database Already added...");
            }
            else
            {
                // add database to the tree
                tree_Selected.Nodes["ADAPT"].Nodes.Add(receivedDb.Key, "Database");
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("WaveForm Data: " + receivedDb.WavFormData);
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("Kinematic Data: " + receivedDb.KinematicData);
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("NamePlate Data: " + receivedDb.NamePlateData);
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("Malfunction Data : " + receivedDb.MalfunctionData);
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("Data Attributes : " + receivedDb.DataAttributes);
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Nodes.Add("Commnets : " + receivedDb.Comments);

                // expand new nodes
                tree_Selected.Nodes["ADAPT"].Expand();
                tree_Selected.Nodes["ADAPT"].Nodes[receivedDb.Key].Expand();
            }
        
        }

        private void populateAdreDatabase()
        {
            ADRE receivedDb = null;

            if (System.Environment.MachineName == "ERICK-PC")
            {
                // add the adapt database to the list
                receivedDb = new ADRE(
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\ADRE Data\DataSet1\ADRESXP_100916_101013_V3.00_FullLoad_MalfunctionTag.txt",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\ADRE Data\DataSet1\NameplateInformation.pdf",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\ADRE Data\DataSet1\Bosch Rexroth 455 60Hz Ratio=85.604.xlsm",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\ADRE Data\DataSet1\Data",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\ADRE Data\DataSet1\Notes\Comments.txt",
                    @"C:\Users\erick\Documents\Senior Projects\UNR Data Analytics\ADRE Data\DataSet1\ConfigDBFile.xml"
                    );
            }
            else
            {
                return;
            }

            databases.Add(receivedDb);

            // if data base hasn't already been added, add it to the tree
            if (tree_Selected.Nodes["ADRE"].Nodes.ContainsKey(receivedDb.Key))
                MessageBox.Show("Database already added...");
            else
            {
                tree_Selected.Nodes["ADRE"].Nodes.Add(receivedDb.Key, "Database");
                tree_Selected.Nodes["ADRE"].Nodes.Add("Waveform Data: " + receivedDb.Waveform);
                tree_Selected.Nodes["ADRE"].Nodes.Add("Kinematic Data: " + receivedDb.Kinematics);
                tree_Selected.Nodes["ADRE"].Nodes.Add("Nameplate Data: " + receivedDb.Nameplate);
                tree_Selected.Nodes["ADRE"].Nodes.Add("Malfunction Data: " + receivedDb.Condition);
                tree_Selected.Nodes["ADRE"].Expand();
                tree_Selected.Nodes["ADRE"].Nodes[receivedDb.Key].Expand();
            }

        }
        public void  populateSystem1Database()
        {
			System1 receivedDb = null;

			if (System.Environment.MachineName.ToLower() == "pat-laptop")
			{
				receivedDb = new System1(new SqlConnection(@"Server=.\V2012;Integrated Security=true"),
					@".\V2012",
					"RiyadhFeb2010_PIB_1_C~Config_2010_03_03T14_46_55",
					"RiyadhFeb2010_SRU_PIB_1_Historical_2010_03_03T14_46_55",
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\System 1 Data\RecipGearBox_100303-Archive_6.87_Unzipped_MalfunctionTag.txt",
					@"C:\Users\Pat York\Documents\School\Senior Projects\UNR Data Analytics\System 1 Data\RecipGearBox_100303-Archive_6.87_Unzipped_Comments.txt");
				textBox_ServerName.Text = @".\V2012";

				databases.Add(receivedDb);

				// Check if this System1 database has already been added to the list
				if (tree_Selected.Nodes["System1"].Nodes.ContainsKey(receivedDb.Key))
				{
					MessageBox.Show("Database Already added...");
				}
				else
				{
					// Add new DB to the tree
					tree_Selected.Nodes["System1"].Nodes.Add(receivedDb.Key, "Database");
					tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Configuration Database: " + receivedDb.ConfigurationDatabaseName);
					tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Historical Database: " + receivedDb.HistoricalDatabaseName);
					tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Malfunction Tags: " + receivedDb.MalfunctionTagFilepath);
					tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Nodes.Add("Segment Ids: " + receivedDb.CommentsFilePath);

					// Expand new nodes
					tree_Selected.Nodes["System1"].Expand();
					tree_Selected.Nodes["System1"].Nodes[receivedDb.Key].Expand();
				}
			}
			
        }
 
		public void populateStandadrdizedDatabases()
		{
			Standardized receivedDb = null;

			if (System.Environment.MachineName.ToLower() == "pat-laptop")
			{
				receivedDb = new Standardized(new SqlConnection(@"Server=.\V2012;Integrated Security=true"), @".\V2012", "ADAPT1");
				textBox_ServerName.Text = @".\V2012";
				databases.Add(receivedDb);

				// Check if this Standardized database has already been added to the list
				if (tree_Selected.Nodes["Standardized"].Nodes.ContainsKey(receivedDb.Key))
				{
					MessageBox.Show("Database Already added...");
				}
				else
				{
					// Add new DB to the tree
					tree_Selected.Nodes["Standardized"].Nodes.Add(receivedDb.Key, "Database");
					tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Nodes.Add("Server: " + receivedDb.ServerName);
					tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Nodes.Add("Standardized Database: " + receivedDb.DatabaseName);

					// Expand new nodes
					tree_Selected.Nodes["Standardized"].Expand();
					tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Expand();
				}

				receivedDb = new Standardized(new SqlConnection(@"Server=.\V2012;Integrated Security=true"), @".\V2012", "System1");
				textBox_ServerName.Text = @".\V2012";
				databases.Add(receivedDb);

				// Check if this Standardized database has already been added to the list
				if (tree_Selected.Nodes["Standardized"].Nodes.ContainsKey(receivedDb.Key))
				{
					MessageBox.Show("Database Already added...");
				}
				else
				{
					// Add new DB to the tree
					tree_Selected.Nodes["Standardized"].Nodes.Add(receivedDb.Key, "Database");
					tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Nodes.Add("Server: " + receivedDb.ServerName);
					tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Nodes.Add("Standardized Database: " + receivedDb.DatabaseName);

					// Expand new nodes
					tree_Selected.Nodes["Standardized"].Expand();
					tree_Selected.Nodes["Standardized"].Nodes[receivedDb.Key].Expand();
				}
			}
		}

        #endregion

		#region Export Functions
		private void textBox_Export_ServerName_TextChanged(object sender, EventArgs e)
		{
			if (textBox_Export_ServerName.Text.Length > 0)
			{
				button_Export_Connect.Enabled = true;
			}
			else
			{
				button_Export_Connect.Enabled = false;
			}
		}

		private void textBox_Export_ServerName_Leave(object sender, EventArgs e)
		{
			if (textBox_Export_ServerName.Text.Length > 0)
			{
				button_Export_Connect.Enabled = true;
			}
			else
			{
				button_Export_Connect.Enabled = false;
			}
		}

		private void button_Export_Connect_Click(object sender, EventArgs e)
		{
			try
			{
				exportConnection = new System.Data.SqlClient.SqlConnection();		// SQL Connection

				// Connect to the given server
				if (dropDown_Export_Auth.SelectedIndex == 0)		// Integrated Security
				{
					exportConnection.ConnectionString = String.Format("Server={0};Integrated Security=true", textBox_Export_ServerName.Text);
				}
				else	// SQL Server Authentication
				{
					exportConnection.ConnectionString = String.Format("Server={0};User ID={1};Password={2}",
						textBox_Export_ServerName.Text, textBox_Export_Username.Text, textBox_Export_Password.Text);
				}

				// Get a list of databases/catalogs
				exportConnection.Open();
				DataTable tbl_databases = exportConnection.GetSchema("Databases");
				exportConnection.Close();

				// Populate dropdown menus
				dropDown_Export_DatabaseName.Items.Clear();

				foreach (DataRow row in tbl_databases.Rows)
				{
					dropDown_Export_DatabaseName.Items.Add(row["database_name"].ToString());
				}

				// Precondition: Connection has been successful
				button_Export_Connect.Enabled = true;
				dropDown_Export_DatabaseName.Enabled = true;

				// Alert user to successful connection
				statusLabel.Text = String.Format("Successfully connected to '{0}'", textBox_Export_ServerName.Text);
			}
			catch (Exception ex)
			{
				exportConnection.Close();
				// Alert user
				MessageBox.Show(String.Format("Unable to connect to server '{0}':\r\n{1}", textBox_Export_ServerName.Text, ex.Message),
					"Connection Unsuccessful!", MessageBoxButtons.OK, MessageBoxIcon.Error);
				exportConnection = null;
			};
		}

		private void dropDown_Export_Auth_SelectedIndexChanged(object sender, EventArgs e)
		{
			if(dropDown_Export_Auth.SelectedIndex == 0)
			{
				textBox_Export_Username.Enabled = false;
				textBox_Export_Password.Enabled = false;
				label_Export_Password.Enabled = false;
				label_Export_UserName.Enabled = false;
			}
			else
			{
				textBox_Export_Username.Enabled = true;
				textBox_Export_Password.Enabled = true;
				label_Export_Password.Enabled = true;
				label_Export_UserName.Enabled = true;
			}
		}

		private void button_ViewSQL_Click(object sender, EventArgs e)
		{
			string Query = GenerateExportSql();

			SaveFileDialog save = new SaveFileDialog();
			save.Filter = "SQL File (.sql)|*.sql";
			if (save.ShowDialog() == DialogResult.OK)
			{
				using (System.IO.StreamWriter sw = new System.IO.StreamWriter(save.FileName))
					sw.WriteLine(Query);

				System.Diagnostics.Process.Start(save.FileName);
			}
		}

		private static string ByteArrayToString(byte[] ba)
		{
			string hex = BitConverter.ToString(ba);
			return hex.Replace("-", "");
		}

		private void button_Export_Click(object sender, EventArgs e)
		{
			string Query = GenerateExportSql();

			DataTable table = null;

			// Execute query
			try
			{
				exportConnection.Open();
				using (SqlDataAdapter adapter = new SqlDataAdapter(Query, exportConnection))
				{
					//adapter.SelectCommand = new SqlCommand(storedProcedure, _connection);
					adapter.SelectCommand.CommandType = CommandType.Text;

					DataSet set = new DataSet();
					adapter.Fill(set);

					table = set.Tables[0];
				}
			}
			catch (SqlException sqlEx)
			{
				exportConnection.Close();
				Console.WriteLine(@"MainForm.cs\\button_Export_Click: " + sqlEx.Message);
			}
			finally
			{
				exportConnection.Close();
			}

			// Store Query
			SaveFileDialog save = new SaveFileDialog();
			save.Filter = "Comma-Separated File (.csv)|*.csv";
			if (save.ShowDialog() == DialogResult.OK)
			{
				using (System.IO.StreamWriter sw = new System.IO.StreamWriter(save.FileName))
				{
					// Output the column headers
					string column_headers = "";
					foreach (DataColumn column in table.Columns)
					{
						column_headers += "\"" + column.ColumnName + "\",";
					}
					sw.WriteLine(column_headers);

					// Output the data
					foreach (DataRow row in table.Rows)
					{
						string line = "";

						for (int i = 0; i < row.ItemArray.Length; i++)
						{
							// If this is a BLOB, output it as a HEX string.
							if (row[i].GetType() == typeof(System.Byte[]))
							{
								line += "\"" + ByteArrayToString((System.Byte[])row[i]) + "\",";
							}
							else // Output as a string
							{
								line += "\"" + row[i].ToString() + "\",";
							}
						}
						sw.WriteLine(line);
					}
				}
			}
		}

		private string GenerateExportSql()
		{
			string query1_Prefix = "SELECT \r\n ";

			if (cb_w_sdata.CheckState != CheckState.Checked) query1_Prefix += "DISTINCT \r\n ";	// No DISTINCT with image data type

			string query3_Joins = String.Format(
				"\r\nFROM [{0}].[dbo].[machine] AS M \r\n" +
				"INNER JOIN [{0}].[dbo].machine_condition AS C ON M.machine_id = C.machine_id \r\n" +
				"INNER JOIN [{0}].[dbo].data_source AS D ON D.data_source_id = C.data_source_id \r\n" +
				"INNER JOIN [{0}].[dbo].stage AS STG ON STG.machine_id = M.machine_id \r\n" +
				"INNER JOIN [{0}].[dbo].sensor AS SENS ON SENS.stage_id = STG.stage_id \r\n" +
				"INNER JOIN [{0}].[dbo].waveform AS W ON W.sensor_id = SENS.sensor_id \r\n" +
				"INNER JOIN [{0}].[dbo].engr_units AS E ON E.engr_unit_id = W.engr_unit_id\r\n",
				dropDown_Export_DatabaseName.SelectedItem);

			List<string> query2_Selects = new List<string>();
			List<string> query4_Filters = new List<string>();

			if (cb_m_id.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("M.[machine_id]");

				if (dd_m_id.SelectedIndex == 1)
				{
					query4_Filters.Add("(M.[machine_id] BETWEEN " + tb_m_id1.Text + " AND " + tb_m_id2.Text + ")");
				}
				else if (dd_m_id.SelectedIndex > 1)
				{
					query4_Filters.Add("(M.[machine_id] " + dd_m_id.SelectedItem + " " + tb_m_id1.Text + " )");
				}
			}
			if (cb_m_type.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("M.[type]");

				if (dd_m_type.SelectedIndex == 1)
				{
					query4_Filters.Add("(M.[type] BETWEEN '" + tb_m_type1.Text + "' AND '" + tb_m_type2.Text + "')");
				}
				else if (dd_m_type.SelectedIndex > 1)
				{
					query4_Filters.Add("(M.[type] " + dd_m_type.SelectedItem + " '" + tb_m_type1.Text + "' )");
				}
			}
			if (cb_m_serial.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("M.[serial_number]");

				if (dd_m_serial.SelectedIndex == 1)
				{
					query4_Filters.Add("(M.[serial_number] BETWEEN '" + tb_m_serial1.Text + "' AND '" + tb_m_serial2.Text + "')");
				}
				else if (dd_m_serial.SelectedIndex > 1)
				{
					query4_Filters.Add("(M.[serial_number] " + dd_m_serial.SelectedItem + " '" + tb_m_serial1.Text + "' )");
				}
			}
			if (cb_m_site.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("M.[site_location]");

				if (dd_m_site.SelectedIndex == 1)
				{
					query4_Filters.Add("(M.[site_location] BETWEEN '" + tb_m_site1.Text + "' AND '" + tb_m_site2.Text + "')");
				}
				else if (dd_m_site.SelectedIndex > 1)
				{
					query4_Filters.Add("(M.[site_location] " + dd_m_site.SelectedItem + " '" + tb_m_site1.Text + "' )");
				}
			}
			if (cb_m_tag.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("M.[tag]");

				if (dd_m_tag.SelectedIndex == 1)
				{
					query4_Filters.Add("(M.[tag] BETWEEN '" + tb_m_tag1.Text + "' AND '" + tb_m_tag2.Text + "')");
				}
				else if (dd_m_tag.SelectedIndex > 1)
				{
					query4_Filters.Add("(M.[tag] " + dd_m_tag.SelectedItem + " '" + tb_m_tag1.Text + "' )");
				}
			}
			if (cb_m_workorder.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("M.[workorder]");

				if (dd_m_workorder.SelectedIndex == 1)
				{
					query4_Filters.Add("(M.[workorder] BETWEEN '" + tb_m_workorder1.Text + "' AND '" + tb_m_workorder2.Text + "')");
				}
				else if (dd_m_workorder.SelectedIndex > 1)
				{
					query4_Filters.Add("(M.[workorder] " + dd_m_workorder.SelectedItem + " '" + tb_m_workorder1.Text + "' )");
				}
			}
			if (cb_m_make.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("M.[make]");

				if (dd_m_make.SelectedIndex == 1)
				{
					query4_Filters.Add("(M.[make] BETWEEN '" + tb_m_make1.Text + "' AND '" + tb_m_make2.Text + "')");
				}
				else if (dd_m_make.SelectedIndex > 1)
				{
					query4_Filters.Add("(M.[make] " + dd_m_make.SelectedItem + " '" + tb_m_make1.Text + "' )");
				}
			}



			if (cb_stage_id.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[stage_id]");

				if (dd_stage_id.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[stage_id] BETWEEN " + tb_stage_id1.Text + " AND " + tb_stage_id2.Text + ")");
				}
				else if (dd_stage_id.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[stage_id] " + dd_stage_id.SelectedItem + " " + tb_stage_id1.Text + " )");
				}
			}
			if (cb_stage_desig.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[designation]");

				if (dd_stage_desig.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[designation] BETWEEN " + tb_stage_desig1.Text + " AND " + tb_stage_desig2.Text + ")");
				}
				else if (dd_stage_desig.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[designation] " + dd_stage_desig.SelectedItem + " " + tb_stage_desig1.Text + " )");
				}
			}
			if (cb_stage_pinion.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[pinion_tooth_count]");

				if (dd_stage_pinion.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[pinion_tooth_count] BETWEEN " + tb_stage_pinion1.Text + " AND " + tb_stage_pinion2.Text + ")");
				}
				else if (dd_stage_pinion.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[pinion_tooth_count] " + dd_stage_pinion.SelectedItem + " " + tb_stage_pinion1.Text + " )");
				}
			}
			if (cb_stage_gear.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[gear_tooth_count]");

				if (dd_stage_gear.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[gear_tooth_count] BETWEEN " + tb_stage_gear1.Text + " AND " + tb_stage_gear2.Text + ")");
				}
				else if (dd_stage_gear.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[gear_tooth_count] " + dd_stage_gear.SelectedItem + " " + tb_stage_gear1.Text + " )");
				}
			}
			if (cb_stage_sun.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[sun_tooth_count]");

				if (dd_stage_sun.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[sun_tooth_count] BETWEEN " + tb_stage_sun1.Text + " AND " + tb_stage_sun2.Text + ")");
				}
				else if (dd_stage_sun.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[sun_tooth_count] " + dd_stage_sun.SelectedItem + " " + tb_stage_sun1.Text + " )");
				}
			}
			if (cb_stage_planet.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[planet_tooth_count]");

				if (dd_stage_planet.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[planet_tooth_count] BETWEEN " + tb_stage_planet1.Text + " AND " + tb_stage_planet2.Text + ")");
				}
				else if (dd_stage_planet.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[planet_tooth_count] " + dd_stage_planet.SelectedItem + " " + tb_stage_planet1.Text + " )");
				}
			}
			if (cb_stage_ring.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[ring_tooth_count]");

				if (dd_stage_ring.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[ring_tooth_count] BETWEEN " + tb_stage_ring1.Text + " AND " + tb_stage_ring2.Text + ")");
				}
				else if (dd_stage_ring.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[ring_tooth_count] " + dd_stage_ring.SelectedItem + " " + tb_stage_ring1.Text + " )");
				}
			}
			if (cb_stage_pcount.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[planet_count]");

				if (dd_stage_pcount.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[planet_count] BETWEEN " + tb_stage_pcount1.Text + " AND " + tb_stage_pcount2.Text + ")");
				}
				else if (dd_stage_pcount.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[planet_count] " + dd_stage_pcount.SelectedItem + " " + tb_stage_pcount1.Text + " )");
				}
			}
			if (cb_stage_fixed.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[fixed]");

				if (dd_stage_fixed.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[fixed] BETWEEN " + tb_stage_fixed1.Text + " AND " + tb_stage_fixed2.Text + ")");
				}
				else if (dd_stage_fixed.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[fixed] " + dd_stage_fixed.SelectedItem + " " + tb_stage_fixed1.Text + " )");
				}
			}
			if (cb_stage_mid.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("STG.[machine_id]");

				if (dd_stage_mid.SelectedIndex == 1)
				{
					query4_Filters.Add("(STG.[machine_id] BETWEEN " + tb_stage_mid1.Text + " AND " + tb_stage_mid2.Text + ")");
				}
				else if (dd_stage_mid.SelectedIndex > 1)
				{
					query4_Filters.Add("(STG.[machine_id] " + dd_stage_mid.SelectedItem + " " + tb_stage_mid1.Text + " )");
				}
			}




			if (cb_sens_id.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("SENS.[sensor_id]");

				if (dd_sens_id.SelectedIndex == 1)
				{
					query4_Filters.Add("(SENS.[sensor_id] BETWEEN " + tb_sens_id1.Text + " AND " + tb_sens_id2.Text + ")");
				}
				else if (dd_sens_id.SelectedIndex > 1)
				{
					query4_Filters.Add("(SENS.[sensor_id] " + dd_sens_id.SelectedItem + " " + tb_sens_id1.Text + " )");
				}
			}
			if (cb_sens_name.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("SENS.[point_name]");

				if (dd_sens_name.SelectedIndex == 1)
				{
					query4_Filters.Add("(SENS.[point_name] BETWEEN '" + tb_sens_name1.Text + "' AND '" + tb_sens_name2.Text + "')");
				}
				else if (dd_sens_name.SelectedIndex > 1)
				{
					query4_Filters.Add("(SENS.[point_name] " + dd_sens_name.SelectedItem + " '" + tb_sens_name1.Text + "' )");
				}
			}
			if (cb_sens_mid.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("SENS.[stage_id]");

				if (dd_sens_mid.SelectedIndex == 1)
				{
					query4_Filters.Add("(SENS.[stage_id] BETWEEN " + tb_sens_mid1.Text + " AND " + tb_sens_mid2.Text + ")");
				}
				else if (dd_sens_mid.SelectedIndex > 1)
				{
					query4_Filters.Add("(SENS.[stage_id] " + dd_sens_mid.SelectedItem + " " + tb_sens_mid1.Text + " )");
				}
			}



			if (cb_d_id.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("D.[data_source_id]");

				if (dd_d_id.SelectedIndex == 1)
				{
					query4_Filters.Add("(D.[data_source_id] BETWEEN " + tb_d_id1.Text + " AND " + tb_d_id2.Text + ")");
				}
				else if (dd_d_id.SelectedIndex > 1)
				{
					query4_Filters.Add("(D.[data_source_id] " + dd_d_id.SelectedItem + " " + tb_d_id1.Text + " )");
				}
			}
			if (cb_d_name.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("D.[name]");

				if (dd_d_name.SelectedIndex == 1)
				{
					query4_Filters.Add("(D.[name] BETWEEN '" + tb_d_name1.Text + "' AND '" + tb_d_name2.Text + "')");
				}
				else if (dd_d_name.SelectedIndex > 1)
				{
					query4_Filters.Add("(D.[name] " + dd_d_name.SelectedItem + " '" + tb_d_name1.Text + "' )");
				}
			}



			if (cb_w_id.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[sensor_id]");

				if (dd_w_id.SelectedIndex == 1)
				{
					query4_Filters.Add("(W.[sensor_id] BETWEEN " + tb_w_id1.Text + " AND " + tb_w_id2.Text + ")");
				}
				else if (dd_w_id.SelectedIndex > 1)
				{
					query4_Filters.Add("(W.[sensor_id] " + dd_w_id.SelectedItem + " " + tb_w_id1.Text + " )");
				}
			}
			if (cb_w_date.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[gmt]");

				if (dd_w_date.SelectedIndex == 1)
				{
					// yyyy/mm/dd
					DateTime dt1 = DateTime.Parse(tb_w_date1.Text);
					DateTime dt2 = DateTime.Parse(tb_w_date2.Text);

					query4_Filters.Add("(W.[gmt] BETWEEN DATETIMEFROMPARTS(" + dt1.Year + "," + dt1.Month + "," + dt1.Day + ",0,0,0,0) " +
						"AND DATETIMEFROMPARTS(" + dt2.Year + "," + dt2.Month + "," + dt2.Day + ",0,0,0,0))");
				}
				else if (dd_w_date.SelectedIndex > 1)
				{
					// yyyy/mm/dd
					DateTime dt1 = DateTime.Parse(tb_w_date1.Text);
					query4_Filters.Add("(W.[gmt] " + dd_w_date.SelectedItem +
						" DATETIMEFROMPARTS(" + dt1.Year + "," + dt1.Month + "," + dt1.Day + ",0,0,0,0))");
				}
			}
			if (cb_w_rpm.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[machine_rpm]");

				if (dd_w_rpm.SelectedIndex == 1)
				{
					query4_Filters.Add("(W.[machine_rpm] BETWEEN " + tb_w_rpm1.Text + " AND " + tb_w_rpm2.Text + ")");
				}
				else if (dd_w_rpm.SelectedIndex > 1)
				{
					query4_Filters.Add("(W.[machine_rpm] " + dd_w_rpm.SelectedItem + " " + tb_w_rpm1.Text + " )");
				}
			}
			if (cb_w_srate.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[sample_rate]");

				if (dd_w_srate.SelectedIndex == 1)
				{
					query4_Filters.Add("(W.[sample_rate] BETWEEN " + tb_w_srate1.Text + " AND " + tb_w_srate2.Text + ")");
				}
				else if (dd_w_srate.SelectedIndex > 1)
				{
					query4_Filters.Add("(W.[sample_rate] " + dd_w_srate.SelectedItem + " " + tb_w_srate1.Text + " )");
				}
			}
			if (cb_w_bitsper.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[bits_per_sample]");

				if (dd_w_bitsper.SelectedIndex == 1)
				{
					query4_Filters.Add("(W.[bits_per_sample] BETWEEN " + tb_w_bitsper1.Text + " AND " + tb_w_bitsper2.Text + ")");
				}
				else if (dd_w_bitsper.SelectedIndex > 1)
				{
					query4_Filters.Add("(W.[bits_per_sample] " + dd_w_bitsper.SelectedItem + " " + tb_w_bitsper1.Text + " )");
				}
			}
			if (cb_w_engrid.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[engr_unit_id]");

				if (dd_w_engrid.SelectedIndex == 1)
				{
					query4_Filters.Add("(W.[engr_unit_id] BETWEEN " + tb_w_engrid1.Text + " AND " + tb_w_engrid2.Text + ")");
				}
				else if (dd_w_engrid.SelectedIndex > 1)
				{
					query4_Filters.Add("(W.[engr_unit_id] " + dd_w_engrid.SelectedItem + " " + tb_w_engrid1.Text + " )");
				}
			}
			if (cb_w_status.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[status]");

				if (dd_w_status.SelectedIndex == 1)
				{
					query4_Filters.Add("(W.[status] BETWEEN " + tb_w_status1.Text + " AND " + tb_w_status2.Text + ")");
				}
				else if (dd_w_status.SelectedIndex > 1)
				{
					query4_Filters.Add("(W.[status] " + dd_w_status.SelectedItem + " " + tb_w_status1.Text + " )");
				}
			}
			if (cb_w_sdata.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("W.[sample_data]");
			}



			if (cb_e_id.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("E.[engr_unit_id]");

				if (dd_e_id.SelectedIndex == 1)
				{
					query4_Filters.Add("(E.[engr_unit_id] BETWEEN " + tb_e_id1.Text + " AND " + tb_e_id2.Text + ")");
				}
				else if (dd_e_id.SelectedIndex > 1)
				{
					query4_Filters.Add("(E.[engr_unit_id] " + dd_e_id.SelectedItem + " " + tb_e_id1.Text + " )");
				}
			}
			if (cb_e_abbrev.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("E.[abbrev]");

				if (dd_e_abbrev.SelectedIndex == 1)
				{
					query4_Filters.Add("(E.[abbrev] BETWEEN '" + tb_e_abbrev1.Text + "' AND '" + tb_e_abbrev2.Text + "')");
				}
				else if (dd_e_abbrev.SelectedIndex > 1)
				{
					query4_Filters.Add("(E.[abbrev] " + dd_e_abbrev.SelectedItem + " '" + tb_e_abbrev1.Text + "' )");
				}
			}
			if (cb_e_mult.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("E.[mult_to_ref]");

				if (dd_e_mult.SelectedIndex == 1)
				{
					query4_Filters.Add("(E.[mult_to_ref] BETWEEN " + tb_e_mult1.Text + " AND " + tb_e_mult2.Text + ")");
				}
				else if (dd_e_mult.SelectedIndex > 1)
				{
					query4_Filters.Add("(E.[mult_to_ref] " + dd_e_mult.SelectedItem + " " + tb_e_mult1.Text + " )");
				}
			}
			if (cb_e_offset.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("E.[offset_to_ref]");

				if (dd_e_offset.SelectedIndex == 1)
				{
					query4_Filters.Add("(E.[offset_to_ref] BETWEEN " + tb_e_offset1.Text + " AND " + tb_e_offset2.Text + ")");
				}
				else if (dd_e_offset.SelectedIndex > 1)
				{
					query4_Filters.Add("(E.[offset_to_ref] " + dd_e_offset.SelectedItem + " " + tb_e_offset1.Text + " )");
				}
			}
			if (cb_e_name.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("E.[name]");

				if (dd_e_name.SelectedIndex == 1)
				{
					query4_Filters.Add("(E.[name] BETWEEN '" + tb_e_name1.Text + "' AND '" + tb_e_name2.Text + "')");
				}
				else if (dd_e_name.SelectedIndex > 1)
				{
					query4_Filters.Add("(E.[name] " + dd_e_name.SelectedItem + " '" + tb_e_name1.Text + "' )");
				}
			}



			if (cb_c_id.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("C.[machine_id]");

				if (dd_c_id.SelectedIndex == 1)
				{
					query4_Filters.Add("(C.[machine_id] BETWEEN " + tb_c_id1.Text + " AND " + tb_c_id2.Text + ")");
				}
				else if (dd_c_id.SelectedIndex > 1)
				{
					query4_Filters.Add("(C.[machine_id] " + dd_c_id.SelectedItem + " " + tb_c_id1.Text + " )");
				}
			}
			if (cb_c_start.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("C.[start_date]");

				if (dd_c_start.SelectedIndex == 1)
				{
					query4_Filters.Add("(C.[start_date] BETWEEN " + tb_c_start1.Text + " AND " + tb_c_start2.Text + ")");
				}
				else if (dd_c_start.SelectedIndex > 1)
				{
					query4_Filters.Add("(C.[start_date] " + dd_c_start.SelectedItem + " " + tb_c_start1.Text + " )");
				}
			}
			if (cb_c_end.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("C.[end_date]");

				if (dd_c_end.SelectedIndex == 1)
				{
					query4_Filters.Add("(C.[end_date] BETWEEN " + tb_c_end1.Text + " AND " + tb_c_end2.Text + ")");
				}
				else if (dd_c_end.SelectedIndex > 1)
				{
					query4_Filters.Add("(C.[end_date] " + dd_c_end.SelectedItem + " " + tb_c_end1.Text + " )");
				}
			}
			if (cb_c_cond.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("C.[condition]");

				if (dd_c_cond.SelectedIndex == 1)
				{
					query4_Filters.Add("(C.[condition] BETWEEN '" + tb_c_cond1.Text + "' AND '" + tb_c_cond2.Text + "')");
				}
				else if (dd_c_cond.SelectedIndex > 1)
				{
					query4_Filters.Add("(C.[condition] " + dd_c_cond.SelectedItem + " '" + tb_c_cond1.Text + "' )");
				}
			}
			if (cb_c_comm.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("C.[comments]");

				if (dd_c_comm.SelectedIndex == 1)
				{
					query4_Filters.Add("(C.[comments] BETWEEN '" + tb_c_comm1.Text + "' AND '" + tb_c_comm2.Text + "')");
				}
				else if (dd_c_comm.SelectedIndex > 1)
				{
					query4_Filters.Add("(C.[comments] " + dd_c_comm.SelectedItem + " '" + tb_c_comm1.Text + "' )");
				}
			}
			if (cb_c_source.CheckState == CheckState.Checked)
			{
				query2_Selects.Add("C.[data_source_id]");

				if (dd_c_source.SelectedIndex == 1)
				{
					query4_Filters.Add("(C.[data_source_id] BETWEEN " + tb_c_source1.Text + " AND " + tb_c_source2.Text + ")");
				}
				else if (dd_c_source.SelectedIndex > 1)
				{
					query4_Filters.Add("(C.[data_source_id] " + dd_c_source.SelectedItem + " " + tb_c_source1.Text + " )");
				}
			}


			// Put the query together
			string Query = query1_Prefix + " ";

			Query += query2_Selects[0] + " ";
			for (int i = 1; i < query2_Selects.Count; i++)
				Query += ",\r\n\t" + query2_Selects[i];

			Query += query3_Joins;

			if (query4_Filters.Count > 0)
			{
				Query += "WHERE\r\n\t" + query4_Filters[0];
				for (int i = 1; i < query4_Filters.Count; i++)
					Query += "\r\n\tAND " + query4_Filters[i];
			}

			return Query;
		}
		#endregion


		#region Check Box Events

		private void cb_m_CheckStateChanged(object sender, EventArgs e)
		{
			if (cb_m.CheckState == CheckState.Checked)	// Now fully checked
			{
				cb_m_id.CheckState = CheckState.Checked;
				cb_m_make.CheckState = CheckState.Checked;
				cb_m_serial.CheckState = CheckState.Checked;
				cb_m_site.CheckState = CheckState.Checked;
				cb_m_tag.CheckState = CheckState.Checked;
				cb_m_type.CheckState = CheckState.Checked;
				cb_m_workorder.CheckState = CheckState.Checked;
			}
			else if (cb_m.CheckState == CheckState.Unchecked)	// Now fully unchecked
			{
				cb_m_id.CheckState = CheckState.Unchecked;
				cb_m_make.CheckState = CheckState.Unchecked;
				cb_m_serial.CheckState = CheckState.Unchecked;
				cb_m_site.CheckState = CheckState.Unchecked;
				cb_m_tag.CheckState = CheckState.Unchecked;
				cb_m_type.CheckState = CheckState.Unchecked;
				cb_m_workorder.CheckState = CheckState.Unchecked;
			}
			else												// Now intermediate
			{
				// Doesn't make sense in this conext, revert to unchecked
				cb_m.CheckState = CheckState.Unchecked;

				cb_m_id.CheckState = CheckState.Unchecked;
				cb_m_make.CheckState = CheckState.Unchecked;
				cb_m_serial.CheckState = CheckState.Unchecked;
				cb_m_site.CheckState = CheckState.Unchecked;
				cb_m_tag.CheckState = CheckState.Unchecked;
				cb_m_type.CheckState = CheckState.Unchecked;
				cb_m_workorder.CheckState = CheckState.Unchecked;
			}
		}

		private void cb_sens_CheckStateChanged(object sender, EventArgs e)
		{
			if (cb_sens.CheckState == CheckState.Checked)	// Now fully checked
			{
				cb_sens_id.CheckState = CheckState.Checked;
				cb_sens_mid.CheckState = CheckState.Checked;
				cb_sens_name.CheckState = CheckState.Checked;
			}
			else if (cb_sens.CheckState == CheckState.Unchecked)	// Now fully unchecked
			{
				cb_sens_id.CheckState = CheckState.Unchecked;
				cb_sens_mid.CheckState = CheckState.Unchecked;
				cb_sens_name.CheckState = CheckState.Unchecked;
			}
			else												// Now intermediate
			{
				// Doesn't make sense in this conext, revert to unchecked
				cb_sens.CheckState = CheckState.Unchecked;

				cb_sens_id.CheckState = CheckState.Unchecked;
				cb_sens_mid.CheckState = CheckState.Unchecked;
				cb_sens_name.CheckState = CheckState.Unchecked;
			}
		}

		private void cb_d_CheckStateChanged(object sender, EventArgs e)
		{
			if (cb_d.CheckState == CheckState.Checked)	// Now fully checked
			{
				cb_d_id.CheckState = CheckState.Checked;
				cb_d_name.CheckState = CheckState.Checked;
			}
			else if (cb_d.CheckState == CheckState.Unchecked)	// Now fully unchecked
			{
				cb_d_id.CheckState = CheckState.Unchecked;
				cb_d_name.CheckState = CheckState.Unchecked;
			}
			else												// Now intermediate
			{
				// Doesn't make sense in this conext, revert to unchecked
				cb_d.CheckState = CheckState.Unchecked;

				cb_d_id.CheckState = CheckState.Unchecked;
				cb_d_name.CheckState = CheckState.Unchecked;
			}
		}

		private void cb_w_CheckStateChanged(object sender, EventArgs e)
		{
			if (cb_w.CheckState == CheckState.Checked)	// Now fully checked
			{
				cb_w_bitsper.CheckState = CheckState.Checked;
				cb_w_date.CheckState = CheckState.Checked;
				cb_w_engrid.CheckState = CheckState.Checked;
				cb_w_id.CheckState = CheckState.Checked;
				cb_w_rpm.CheckState = CheckState.Checked;
				cb_w_sdata.CheckState = CheckState.Checked;
				cb_w_srate.CheckState = CheckState.Checked;
				cb_w_status.CheckState = CheckState.Checked;
			}
			else if (cb_w.CheckState == CheckState.Unchecked)	// Now fully unchecked
			{
				cb_w_bitsper.CheckState = CheckState.Unchecked;
				cb_w_date.CheckState = CheckState.Unchecked;
				cb_w_engrid.CheckState = CheckState.Unchecked;
				cb_w_id.CheckState = CheckState.Unchecked;
				cb_w_rpm.CheckState = CheckState.Unchecked;
				cb_w_sdata.CheckState = CheckState.Unchecked;
				cb_w_srate.CheckState = CheckState.Unchecked;
				cb_w_status.CheckState = CheckState.Unchecked;
			}
			else												// Now intermediate
			{
				// Doesn't make sense in this conext, revert to unchecked
				cb_w.CheckState = CheckState.Unchecked;

				cb_w_bitsper.CheckState = CheckState.Unchecked;
				cb_w_date.CheckState = CheckState.Unchecked;
				cb_w_engrid.CheckState = CheckState.Unchecked;
				cb_w_id.CheckState = CheckState.Unchecked;
				cb_w_rpm.CheckState = CheckState.Unchecked;
				cb_w_sdata.CheckState = CheckState.Unchecked;
				cb_w_srate.CheckState = CheckState.Unchecked;
				cb_w_status.CheckState = CheckState.Unchecked;
			}
		}

		private void cb_stage_CheckStateChanged(object sender, EventArgs e)
		{
			if (cb_stage.CheckState == CheckState.Checked)	// Now fully checked
			{
				cb_stage_desig.CheckState = CheckState.Checked;
				cb_stage_fixed.CheckState = CheckState.Checked;
				cb_stage_gear.CheckState = CheckState.Checked;
				cb_stage_id.CheckState = CheckState.Checked;
				cb_stage_mid.CheckState = CheckState.Checked;
				cb_stage_pcount.CheckState = CheckState.Checked;
				cb_stage_pinion.CheckState = CheckState.Checked;
				cb_stage_planet.CheckState = CheckState.Checked;
				cb_stage_ring.CheckState = CheckState.Checked;
				cb_stage_sun.CheckState = CheckState.Checked;
			}
			else if (cb_stage.CheckState == CheckState.Unchecked)	// Now fully unchecked
			{
				cb_stage_desig.CheckState = CheckState.Unchecked;
				cb_stage_fixed.CheckState = CheckState.Unchecked;
				cb_stage_gear.CheckState = CheckState.Unchecked;
				cb_stage_id.CheckState = CheckState.Unchecked;
				cb_stage_mid.CheckState = CheckState.Unchecked;
				cb_stage_pcount.CheckState = CheckState.Unchecked;
				cb_stage_pinion.CheckState = CheckState.Unchecked;
				cb_stage_planet.CheckState = CheckState.Unchecked;
				cb_stage_ring.CheckState = CheckState.Unchecked;
				cb_stage_sun.CheckState = CheckState.Unchecked;
			}
			else												// Now intermediate
			{
				cb_stage.CheckState = CheckState.Unchecked;

				cb_stage_desig.CheckState = CheckState.Unchecked;
				cb_stage_fixed.CheckState = CheckState.Unchecked;
				cb_stage_gear.CheckState = CheckState.Unchecked;
				cb_stage_id.CheckState = CheckState.Unchecked;
				cb_stage_mid.CheckState = CheckState.Unchecked;
				cb_stage_pcount.CheckState = CheckState.Unchecked;
				cb_stage_pinion.CheckState = CheckState.Unchecked;
				cb_stage_planet.CheckState = CheckState.Unchecked;
				cb_stage_ring.CheckState = CheckState.Unchecked;
				cb_stage_sun.CheckState = CheckState.Unchecked;
			}
		}

		private void cb_e_CheckStateChanged(object sender, EventArgs e)
		{
			if (cb_e.CheckState == CheckState.Checked)	// Now fully checked
			{
				cb_e_abbrev.CheckState = CheckState.Checked;
				cb_e_id.CheckState = CheckState.Checked;
				cb_e_mult.CheckState = CheckState.Checked;
				cb_e_name.CheckState = CheckState.Checked;
				cb_e_offset.CheckState = CheckState.Checked;
			}
			else if (cb_e.CheckState == CheckState.Unchecked)	// Now fully unchecked
			{
				cb_e_abbrev.CheckState = CheckState.Unchecked;
				cb_e_id.CheckState = CheckState.Unchecked;
				cb_e_mult.CheckState = CheckState.Unchecked;
				cb_e_name.CheckState = CheckState.Unchecked;
				cb_e_offset.CheckState = CheckState.Unchecked;
			}
			else												// Now intermediate
			{
				// Doesn't make sense in this conext, revert to unchecked
				cb_e.CheckState = CheckState.Unchecked;

				cb_e_abbrev.CheckState = CheckState.Unchecked;
				cb_e_id.CheckState = CheckState.Unchecked;
				cb_e_mult.CheckState = CheckState.Unchecked;
				cb_e_name.CheckState = CheckState.Unchecked;
				cb_e_offset.CheckState = CheckState.Unchecked;
			}
		}

		private void cb_c_CheckStateChanged(object sender, EventArgs e)
		{
			if (cb_c.CheckState == CheckState.Checked)	// Now fully checked
			{
				cb_c_comm.CheckState = CheckState.Checked;
				cb_c_cond.CheckState = CheckState.Checked;
				cb_c_end.CheckState = CheckState.Checked;
				cb_c_id.CheckState = CheckState.Checked;
				cb_c_source.CheckState = CheckState.Checked;
				cb_c_start.CheckState = CheckState.Checked;
			}
			else if (cb_c.CheckState == CheckState.Unchecked)	// Now fully unchecked
			{
				cb_c_comm.CheckState = CheckState.Unchecked;
				cb_c_cond.CheckState = CheckState.Unchecked;
				cb_c_end.CheckState = CheckState.Unchecked;
				cb_c_id.CheckState = CheckState.Unchecked;
				cb_c_source.CheckState = CheckState.Unchecked;
				cb_c_start.CheckState = CheckState.Unchecked;
			}
			else												// Now intermediate
			{
				// Doesn't make sense in this conext, revert to unchecked
				cb_c.CheckState = CheckState.Unchecked;

				cb_c_comm.CheckState = CheckState.Unchecked;
				cb_c_cond.CheckState = CheckState.Unchecked;
				cb_c_end.CheckState = CheckState.Unchecked;
				cb_c_id.CheckState = CheckState.Unchecked;
				cb_c_source.CheckState = CheckState.Unchecked;
				cb_c_start.CheckState = CheckState.Unchecked;
			}
		}

		private void UpdateMachineParent()
		{
			if (cb_m_id.CheckState == CheckState.Checked && cb_m_make.CheckState == CheckState.Checked &&
				cb_m_serial.CheckState == CheckState.Checked && cb_m_site.CheckState == CheckState.Checked &&
				cb_m_tag.CheckState == CheckState.Checked && cb_m_type.CheckState == CheckState.Checked &&
				cb_m_workorder.CheckState == CheckState.Checked)
			{
				cb_m.CheckState = CheckState.Checked;
			}
			else if (cb_m_id.CheckState == CheckState.Checked || cb_m_make.CheckState == CheckState.Checked ||
				cb_m_serial.CheckState == CheckState.Checked || cb_m_site.CheckState == CheckState.Checked ||
				cb_m_tag.CheckState == CheckState.Checked || cb_m_type.CheckState == CheckState.Checked ||
				cb_m_workorder.CheckState == CheckState.Checked)
			{
				cb_m.CheckState = CheckState.Indeterminate;
			}
			else
			{
				cb_m.CheckState = CheckState.Unchecked;
			}
		}

		private void UpdateSensorParent()
		{
			if (cb_sens_id.CheckState == CheckState.Checked && cb_sens_mid.CheckState == CheckState.Checked &&
				cb_sens_name.CheckState == CheckState.Checked)
			{
				cb_sens.CheckState = CheckState.Checked;
			}
			else if (cb_sens_id.CheckState == CheckState.Checked || cb_sens_mid.CheckState == CheckState.Checked ||
				cb_sens_name.CheckState == CheckState.Checked)
			{
				cb_sens.CheckState = CheckState.Indeterminate;
			}
			else
			{
				cb_sens.CheckState = CheckState.Unchecked;
			}
		}

		private void UpdateDataSourceParent()
		{
			if (cb_d_id.CheckState == CheckState.Checked && cb_d_name.CheckState == CheckState.Checked)
			{
				cb_d.CheckState = CheckState.Checked;
			}
			else if (cb_d_id.CheckState == CheckState.Checked || cb_d_name.CheckState == CheckState.Checked)
			{
				cb_d.CheckState = CheckState.Indeterminate;
			}
			else
			{
				cb_d.CheckState = CheckState.Unchecked;
			}
		}

		private void UpdateWaveformParent()
		{
			if (cb_w_bitsper.CheckState == CheckState.Checked && cb_w_date.CheckState == CheckState.Checked
				&& cb_w_engrid.CheckState == CheckState.Checked && cb_w_id.CheckState == CheckState.Checked
				&& cb_w_rpm.CheckState == CheckState.Checked && cb_w_sdata.CheckState == CheckState.Checked
				&& cb_w_srate.CheckState == CheckState.Checked && cb_w_status.CheckState == CheckState.Checked)
			{
				cb_w.CheckState = CheckState.Checked;
			}
			else if (cb_w_bitsper.CheckState == CheckState.Checked || cb_w_date.CheckState == CheckState.Checked
				|| cb_w_engrid.CheckState == CheckState.Checked || cb_w_id.CheckState == CheckState.Checked
				|| cb_w_rpm.CheckState == CheckState.Checked || cb_w_sdata.CheckState == CheckState.Checked
				|| cb_w_srate.CheckState == CheckState.Checked || cb_w_status.CheckState == CheckState.Checked)
			{
				cb_w.CheckState = CheckState.Indeterminate;
			}
			else
			{
				cb_w.CheckState = CheckState.Unchecked;

			}
		}

		private void UpdateStageParent()
		{
			if (cb_stage_desig.CheckState == CheckState.Checked && cb_stage_fixed.CheckState == CheckState.Checked
				&& cb_stage_gear.CheckState == CheckState.Checked && cb_stage_id.CheckState == CheckState.Checked
				&& cb_stage_mid.CheckState == CheckState.Checked && cb_stage_pcount.CheckState == CheckState.Checked
				&& cb_stage_pinion.CheckState == CheckState.Checked && cb_stage_planet.CheckState == CheckState.Checked
				&& cb_stage_ring.CheckState == CheckState.Checked && cb_stage_sun.CheckState == CheckState.Checked)
			{
				cb_stage.CheckState = CheckState.Checked;
			}
			else if (cb_stage_desig.CheckState == CheckState.Checked || cb_stage_fixed.CheckState == CheckState.Checked
				|| cb_stage_gear.CheckState == CheckState.Checked || cb_stage_id.CheckState == CheckState.Checked
				|| cb_stage_mid.CheckState == CheckState.Checked || cb_stage_pcount.CheckState == CheckState.Checked
				|| cb_stage_pinion.CheckState == CheckState.Checked || cb_stage_planet.CheckState == CheckState.Checked
				|| cb_stage_ring.CheckState == CheckState.Checked || cb_stage_sun.CheckState == CheckState.Checked)
			{
				cb_stage.CheckState = CheckState.Indeterminate;
			}
			else
			{
				cb_stage.CheckState = CheckState.Unchecked;
			}
		}

		private void UpdateEngrUnitParent()
		{
			if (cb_e_abbrev.CheckState == CheckState.Checked && cb_e_id.CheckState == CheckState.Checked
				&& cb_e_mult.CheckState == CheckState.Checked && cb_e_name.CheckState == CheckState.Checked
				&& cb_e_offset.CheckState == CheckState.Checked)
			{
				cb_e.CheckState = CheckState.Checked;
			}
			else if (cb_e_abbrev.CheckState == CheckState.Checked || cb_e_id.CheckState == CheckState.Checked
				|| cb_e_mult.CheckState == CheckState.Checked || cb_e_name.CheckState == CheckState.Checked
				|| cb_e_offset.CheckState == CheckState.Checked)
			{
				cb_e.CheckState = CheckState.Indeterminate;
			}
			else
			{
				cb_e.CheckState = CheckState.Unchecked;
			}
		}

		private void UpdateConditionParent()
		{
			if (cb_c_comm.CheckState == CheckState.Checked && cb_c_cond.CheckState == CheckState.Checked
				&& cb_c_end.CheckState == CheckState.Checked && cb_c_id.CheckState == CheckState.Checked
				&& cb_c_source.CheckState == CheckState.Checked && cb_c_start.CheckState == CheckState.Checked)
			{
				cb_c.CheckState = CheckState.Checked;
			}
			else if (cb_c_comm.CheckState == CheckState.Checked || cb_c_cond.CheckState == CheckState.Checked
				|| cb_c_end.CheckState == CheckState.Checked || cb_c_id.CheckState == CheckState.Checked
				|| cb_c_source.CheckState == CheckState.Checked || cb_c_start.CheckState == CheckState.Checked)
			{
				cb_c.CheckState = CheckState.Indeterminate;
			}
			else
			{
				cb_c.CheckState = CheckState.Unchecked;
			}
		}

		private void cb_m_id_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateMachineParent();
			if (cb_m_id.CheckState == CheckState.Checked) dd_m_id.Enabled = true; 
			else
			{
				dd_m_id.Enabled = false;
				tb_m_id1.Enabled = false;
				tb_m_id2.Enabled = false;
			}
		}

		private void cb_m_type_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateMachineParent();
			if (cb_m_type.CheckState == CheckState.Checked) dd_m_type.Enabled = true;
			else
			{
				dd_m_type.Enabled = false;
			}
		}

		private void cb_m_serial_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateMachineParent();
			if (cb_m_serial.CheckState == CheckState.Checked) dd_m_serial.Enabled = true;
			else
			{
				dd_m_serial.Enabled = false;
			}
		}

		private void cb_m_site_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateMachineParent();
			if (cb_m_site.CheckState == CheckState.Checked) dd_m_site.Enabled = true;
			else
			{
				dd_m_site.Enabled = false;
			}
		}

		private void cb_m_tag_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateMachineParent();
			if (cb_m_tag.CheckState == CheckState.Checked) dd_m_tag.Enabled = true;
			else
			{
				dd_m_tag.Enabled = false;
			}
		}

		private void cb_m_workorder_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateMachineParent();
			if (cb_m_workorder.CheckState == CheckState.Checked) dd_m_workorder.Enabled = true;
			else
			{
				dd_m_workorder.Enabled = false;
			}
		}

		private void cb_m_make_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateMachineParent();
			if (cb_m_make.CheckState == CheckState.Checked) dd_m_make.Enabled = true;
			else
			{
				dd_m_make.Enabled = false;
			}
		}

		private void cb_sens_id_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateSensorParent();
			if (cb_sens_id.CheckState == CheckState.Checked) dd_sens_id.Enabled = true;
			else
			{
				dd_sens_id.Enabled = false;
			}
		}

		private void cb_sens_name_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateSensorParent();
			if (cb_sens_name.CheckState == CheckState.Checked) dd_sens_name.Enabled = true;
			else
			{
				dd_sens_name.Enabled = false;
			}
		}

		private void cb_sens_mid_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateSensorParent();
			if (cb_sens_mid.CheckState == CheckState.Checked) dd_sens_mid.Enabled = true;
			else
			{
				dd_sens_mid.Enabled = false;
			}
		}

		private void cb_d_id_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateDataSourceParent();
			if (cb_d_id.CheckState == CheckState.Checked) dd_d_id.Enabled = true;
			else
			{
				dd_d_id.Enabled = false;
			}
		}

		private void cb_d_name_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateDataSourceParent();
			if (cb_d_name.CheckState == CheckState.Checked) dd_d_name.Enabled = true;
			else
			{
				dd_d_name.Enabled = false;
			}
		}

		private void cb_w_id_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
			if (cb_w_id.CheckState == CheckState.Checked) dd_w_id.Enabled = true;
			else
			{
				dd_w_id.Enabled = false;
			}
		}

		private void cb_w_date_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
			if (cb_w_date.CheckState == CheckState.Checked) dd_w_date.Enabled = true;
			else
			{
				dd_w_date.Enabled = false;
			}
		}

		private void cb_w_rpm_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
			if (cb_w_rpm.CheckState == CheckState.Checked) dd_w_rpm.Enabled = true;
			else
			{
				dd_w_rpm.Enabled = false;
			}
		}

		private void cb_w_srate_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
			if (cb_w_srate.CheckState == CheckState.Checked) dd_w_srate.Enabled = true;
			else
			{
				dd_w_srate.Enabled = false;
			}
		}

		private void cb_w_bitsper_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
			if (cb_w_bitsper.CheckState == CheckState.Checked) dd_w_bitsper.Enabled = true;
			else
			{
				dd_w_bitsper.Enabled = false;
			}
		}

		private void cb_w_engrid_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
			if (cb_w_engrid.CheckState == CheckState.Checked) dd_w_engrid.Enabled = true;
			else
			{
				dd_w_engrid.Enabled = false;
			}
		}

		private void cb_w_status_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
			if (cb_w_status.CheckState == CheckState.Checked) dd_w_status.Enabled = true;
			else
			{
				dd_w_status.Enabled = false;
			}
		}

		private void cb_w_sdata_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateWaveformParent();
		}

		private void cb_stage_id_CheckStateChanged(object sender, EventArgs e)
		{

			UpdateStageParent();
			if (cb_stage_id.CheckState == CheckState.Checked) dd_stage_id.Enabled = true;
			else
			{
				dd_stage_id.Enabled = false;
			}
		}

		private void cb_stage_desig_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_desig.CheckState == CheckState.Checked) dd_stage_desig.Enabled = true;
			else
			{
				dd_stage_desig.Enabled = false;
			}
		}

		private void cb_stage_pinion_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_pinion.CheckState == CheckState.Checked) dd_stage_pinion.Enabled = true;
			else
			{
				dd_stage_pinion.Enabled = false;
			}
		}

		private void cb_stage_gear_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_gear.CheckState == CheckState.Checked) dd_stage_gear.Enabled = true;
			else
			{
				dd_stage_gear.Enabled = false;
			}
		}

		private void cb_stage_sun_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_sun.CheckState == CheckState.Checked) dd_stage_sun.Enabled = true;
			else
			{
				dd_stage_sun.Enabled = false;
			}
		}

		private void cb_stage_planet_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_planet.CheckState == CheckState.Checked) dd_stage_planet.Enabled = true;
			else
			{
				dd_stage_planet.Enabled = false;
			}
		}

		private void cb_stage_ring_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_ring.CheckState == CheckState.Checked) dd_stage_ring.Enabled = true;
			else
			{
				dd_stage_ring.Enabled = false;
			}
		}

		private void cb_stage_pcount_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_pcount.CheckState == CheckState.Checked) dd_stage_pcount.Enabled = true;
			else
			{
				dd_stage_pcount.Enabled = false;
			}
		}

		private void cb_stage_fixed_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_fixed.CheckState == CheckState.Checked) dd_stage_fixed.Enabled = true;
			else
			{
				dd_stage_fixed.Enabled = false;
			}
		}

		private void cb_stage_mid_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateStageParent();
			if (cb_stage_mid.CheckState == CheckState.Checked) dd_stage_mid.Enabled = true;
			else
			{
				dd_stage_mid.Enabled = false;
			}
		}

		private void cb_e_id_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateEngrUnitParent();
			if (cb_e_id.CheckState == CheckState.Checked) dd_e_id.Enabled = true;
			else
			{
				dd_e_id.Enabled = false;
			}
		}

		private void cb_e_abbrev_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateEngrUnitParent();
			if (cb_e_abbrev.CheckState == CheckState.Checked) dd_e_abbrev.Enabled = true;
			else
			{
				dd_e_abbrev.Enabled = false;
			}
		}

		private void cb_e_mult_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateEngrUnitParent();
			if (cb_e_mult.CheckState == CheckState.Checked) dd_e_mult.Enabled = true;
			else
			{
				dd_e_mult.Enabled = false;
			}
		}

		private void cb_e_offset_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateEngrUnitParent();
			if (cb_e_offset.CheckState == CheckState.Checked) dd_e_offset.Enabled = true;
			else
			{
				dd_e_offset.Enabled = false;
			}
		}

		private void cb_e_name_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateEngrUnitParent();
			if (cb_e_name.CheckState == CheckState.Checked) dd_e_name.Enabled = true;
			else
			{
				dd_e_name.Enabled = false;
			}
		}

		private void cb_c_id_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateConditionParent();
			if (cb_c_id.CheckState == CheckState.Checked) dd_c_id.Enabled = true;
			else
			{
				dd_c_id.Enabled = false;
			}
		}

		private void cb_c_start_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateConditionParent();
			if (cb_c_start.CheckState == CheckState.Checked) dd_c_start.Enabled = true;
			else
			{
				dd_c_start.Enabled = false;
			}
		}

		private void cb_c_end_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateConditionParent();
			if (cb_c_end.CheckState == CheckState.Checked) dd_c_end.Enabled = true;
			else
			{
				dd_c_end.Enabled = false;
			}
		}

		private void cb_c_cond_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateConditionParent();
			if (cb_c_cond.CheckState == CheckState.Checked) dd_c_cond.Enabled = true;
			else
			{
				dd_c_cond.Enabled = false;
			}
		}

		private void cb_c_comm_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateConditionParent();
			if (cb_c_comm.CheckState == CheckState.Checked) dd_c_comm.Enabled = true;
			else
			{
				dd_c_comm.Enabled = false;
			}
		}

		private void cb_c_source_CheckStateChanged(object sender, EventArgs e)
		{
			UpdateConditionParent();
			if (cb_c_source.CheckState == CheckState.Checked) dd_c_source.Enabled = true;
			else
			{
				dd_c_source.Enabled = false;
			}
		}
		#endregion

		#region Drop Down Events
		private void dd_m_id_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_m_id1.Enabled = true;
				tb_m_id2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_m_id1.Enabled = true;
				tb_m_id2.Enabled = false;
			}
			else
			{
				tb_m_id1.Enabled = false;
				tb_m_id2.Enabled = false;
			}
		}

		private void dd_m_type_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_m_type1.Enabled = true;
				tb_m_type2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_m_type1.Enabled = true;
				tb_m_type2.Enabled = false;
			}
			else
			{
				tb_m_type1.Enabled = false;
				tb_m_type2.Enabled = false;
			}
		}

		private void dd_m_serial_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_m_serial1.Enabled = true;
				tb_m_serial2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_m_serial1.Enabled = true;
				tb_m_serial2.Enabled = false;
			}
			else
			{
				tb_m_serial1.Enabled = false;
				tb_m_serial2.Enabled = false;
			}
		}

		private void dd_m_site_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_m_site1.Enabled = true;
				tb_m_site2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_m_site1.Enabled = true;
				tb_m_site2.Enabled = false;
			}
			else
			{
				tb_m_site1.Enabled = false;
				tb_m_site2.Enabled = false;
			}
		}

		private void dd_m_tag_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_m_tag1.Enabled = true;
				tb_m_tag2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_m_tag1.Enabled = true;
				tb_m_tag2.Enabled = false;
			}
			else
			{
				tb_m_tag1.Enabled = false;
				tb_m_tag2.Enabled = false;
			}
		}

		private void dd_m_workorder_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_m_workorder1.Enabled = true;
				tb_m_workorder2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_m_workorder1.Enabled = true;
				tb_m_workorder2.Enabled = false;
			}
			else
			{
				tb_m_workorder1.Enabled = false;
				tb_m_workorder2.Enabled = false;
			}
		}

		private void dd_m_make_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_m_make1.Enabled = true;
				tb_m_make2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_m_make1.Enabled = true;
				tb_m_make2.Enabled = false;
			}
			else
			{
				tb_m_make1.Enabled = false;
				tb_m_make2.Enabled = false;
			}
		}

		private void dd_sens_id_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_sens_id1.Enabled = true;
				tb_sens_id2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_sens_id1.Enabled = true;
				tb_sens_id2.Enabled = false;
			}
			else
			{
				tb_sens_id1.Enabled = false;
				tb_sens_id2.Enabled = false;
			}
		}

		private void dd_sens_name_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_sens_name1.Enabled = true;
				tb_sens_name2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_sens_name1.Enabled = true;
				tb_sens_name2.Enabled = false;
			}
			else
			{
				tb_sens_name1.Enabled = false;
				tb_sens_name2.Enabled = false;
			}
		}

		private void dd_sens_mid_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_sens_mid1.Enabled = true;
				tb_sens_mid2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_sens_mid1.Enabled = true;
				tb_sens_mid2.Enabled = false;
			}
			else
			{
				tb_sens_mid1.Enabled = false;
				tb_sens_mid2.Enabled = false;
			}
		}

		private void dd_d_id_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_d_id1.Enabled = true;
				tb_d_id2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_d_id1.Enabled = true;
				tb_d_id2.Enabled = false;
			}
			else
			{
				tb_d_id1.Enabled = false;
				tb_d_id2.Enabled = false;
			}
		}

		private void dd_d_name_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_d_name1.Enabled = true;
				tb_d_name2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_d_name1.Enabled = true;
				tb_d_name2.Enabled = false;
			}
			else
			{
				tb_d_name1.Enabled = false;
				tb_d_name2.Enabled = false;
			}
		}

		private void dd_w_id_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_w_id1.Enabled = true;
				tb_w_id2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_w_id1.Enabled = true;
				tb_w_id2.Enabled = false;
			}
			else
			{
				tb_w_id1.Enabled = false;
				tb_w_id2.Enabled = false;
			}
		}

		private void dd_w_date_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_w_date1.Enabled = true;
				tb_w_date2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_w_date1.Enabled = true;
				tb_w_date2.Enabled = false;
			}
			else
			{
				tb_w_date1.Enabled = false;
				tb_w_date2.Enabled = false;
			}
		}

		private void dd_w_rpm_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_w_rpm1.Enabled = true;
				tb_w_rpm2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_w_rpm1.Enabled = true;
				tb_w_rpm2.Enabled = false;
			}
			else
			{
				tb_w_rpm1.Enabled = false;
				tb_w_rpm2.Enabled = false;
			}
		}

		private void dd_w_srate_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_w_srate1.Enabled = true;
				tb_w_srate2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_w_srate1.Enabled = true;
				tb_w_srate2.Enabled = false;
			}
			else
			{
				tb_w_srate1.Enabled = false;
				tb_w_srate2.Enabled = false;
			}
		}

		private void dd_w_bitsper_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_w_bitsper1.Enabled = true;
				tb_w_bitsper2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_w_bitsper1.Enabled = true;
				tb_w_bitsper2.Enabled = false;
			}
			else
			{
				tb_w_bitsper1.Enabled = false;
				tb_w_bitsper2.Enabled = false;
			}
		}

		private void dd_w_engrid_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_w_engrid1.Enabled = true;
				tb_w_engrid2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_w_engrid1.Enabled = true;
				tb_w_engrid2.Enabled = false;
			}
			else
			{
				tb_w_engrid1.Enabled = false;
				tb_w_engrid2.Enabled = false;
			}
		}

		private void dd_w_status_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_w_status1.Enabled = true;
				tb_w_status2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_w_status1.Enabled = true;
				tb_w_status2.Enabled = false;
			}
			else
			{
				tb_w_status1.Enabled = false;
				tb_w_status2.Enabled = false;
			}
		}



		private void dd_stage_id_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_id1.Enabled = true;
				tb_stage_id2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_id1.Enabled = true;
				tb_stage_id2.Enabled = false;
			}
			else
			{
				tb_stage_id1.Enabled = false;
				tb_stage_id2.Enabled = false;
			}
		}

		private void dd_stage_desig_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_desig1.Enabled = true;
				tb_stage_desig2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_desig1.Enabled = true;
				tb_stage_desig2.Enabled = false;
			}
			else
			{
				tb_stage_desig1.Enabled = false;
				tb_stage_desig2.Enabled = false;
			}
		}

		private void dd_stage_pinion_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_pinion1.Enabled = true;
				tb_stage_pinion2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_pinion1.Enabled = true;
				tb_stage_pinion2.Enabled = false;
			}
			else
			{
				tb_stage_pinion1.Enabled = false;
				tb_stage_pinion2.Enabled = false;
			}
		}

		private void dd_stage_gear_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_gear1.Enabled = true;
				tb_stage_gear2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_gear1.Enabled = true;
				tb_stage_gear2.Enabled = false;
			}
			else
			{
				tb_stage_gear1.Enabled = false;
				tb_stage_gear2.Enabled = false;
			}
		}

		private void dd_stage_sun_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_sun1.Enabled = true;
				tb_stage_sun2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_sun1.Enabled = true;
				tb_stage_sun2.Enabled = false;
			}
			else
			{
				tb_stage_sun1.Enabled = false;
				tb_stage_sun2.Enabled = false;
			}
		}

		private void dd_stage_planet_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_planet1.Enabled = true;
				tb_stage_planet2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_planet1.Enabled = true;
				tb_stage_planet2.Enabled = false;
			}
			else
			{
				tb_stage_planet1.Enabled = false;
				tb_stage_planet2.Enabled = false;
			}
		}

		private void dd_stage_ring_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_ring1.Enabled = true;
				tb_stage_ring2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_ring1.Enabled = true;
				tb_stage_ring2.Enabled = false;
			}
			else
			{
				tb_stage_ring1.Enabled = false;
				tb_stage_ring2.Enabled = false;
			}
		}

		private void dd_stage_pcount_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_pcount1.Enabled = true;
				tb_stage_pcount2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_pcount1.Enabled = true;
				tb_stage_pcount2.Enabled = false;
			}
			else
			{
				tb_stage_pcount1.Enabled = false;
				tb_stage_pcount2.Enabled = false;
			}
		}

		private void dd_stage_fixed_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_fixed1.Enabled = true;
				tb_stage_fixed2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_fixed1.Enabled = true;
				tb_stage_fixed2.Enabled = false;
			}
			else
			{
				tb_stage_fixed1.Enabled = false;
				tb_stage_fixed2.Enabled = false;
			}
		}

		private void dd_stage_mid_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_stage_mid1.Enabled = true;
				tb_stage_mid2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_stage_mid1.Enabled = true;
				tb_stage_mid2.Enabled = false;
			}
			else
			{
				tb_stage_mid1.Enabled = false;
				tb_stage_mid2.Enabled = false;
			}
		}

		private void dd_e_id_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_e_id1.Enabled = true;
				tb_e_id2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_e_id1.Enabled = true;
				tb_e_id2.Enabled = false;
			}
			else
			{
				tb_e_id1.Enabled = false;
				tb_e_id2.Enabled = false;
			}
		}

		private void dd_e_abbrev_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_e_abbrev1.Enabled = true;
				tb_e_abbrev2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_e_abbrev1.Enabled = true;
				tb_e_abbrev2.Enabled = false;
			}
			else
			{
				tb_e_abbrev1.Enabled = false;
				tb_e_abbrev2.Enabled = false;
			}
		}

		private void dd_e_mult_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_e_mult1.Enabled = true;
				tb_e_mult2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_e_mult1.Enabled = true;
				tb_e_mult2.Enabled = false;
			}
			else
			{
				tb_e_mult1.Enabled = false;
				tb_e_mult2.Enabled = false;
			}
		}

		private void dd_e_offset_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_e_offset1.Enabled = true;
				tb_e_offset2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_e_offset1.Enabled = true;
				tb_e_offset2.Enabled = false;
			}
			else
			{
				tb_e_offset1.Enabled = false;
				tb_e_offset2.Enabled = false;
			}
		}

		private void dd_e_name_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_e_name1.Enabled = true;
				tb_e_name2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_e_name1.Enabled = true;
				tb_e_name2.Enabled = false;
			}
			else
			{
				tb_e_name1.Enabled = false;
				tb_e_name2.Enabled = false;
			}
		}

		private void dd_c_id_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_c_id1.Enabled = true;
				tb_c_id2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_c_id1.Enabled = true;
				tb_c_id2.Enabled = false;
			}
			else
			{
				tb_c_id1.Enabled = false;
				tb_c_id2.Enabled = false;
			}
		}

		private void dd_c_start_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_c_start1.Enabled = true;
				tb_c_start2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_c_start1.Enabled = true;
				tb_c_start2.Enabled = false;
			}
			else
			{
				tb_c_start1.Enabled = false;
				tb_c_start2.Enabled = false;
			}
		}

		private void dd_c_end_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_c_end1.Enabled = true;
				tb_c_end2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_c_end1.Enabled = true;
				tb_c_end2.Enabled = false;
			}
			else
			{
				tb_c_end1.Enabled = false;
				tb_c_end2.Enabled = false;
			}
		}

		private void dd_c_cond_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_c_cond1.Enabled = true;
				tb_c_cond2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_c_cond1.Enabled = true;
				tb_c_cond2.Enabled = false;
			}
			else
			{
				tb_c_cond1.Enabled = false;
				tb_c_cond2.Enabled = false;
			}
		}

		private void dd_c_comm_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_c_comm1.Enabled = true;
				tb_c_comm2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_c_comm1.Enabled = true;
				tb_c_comm2.Enabled = false;
			}
			else
			{
				tb_c_comm1.Enabled = false;
				tb_c_comm2.Enabled = false;
			}
		}

		private void dd_c_source_SelectedIndexChanged(object sender, EventArgs e)
		{
			if (((ComboBox)sender).SelectedIndex == 1)
			{
				tb_c_source1.Enabled = true;
				tb_c_source2.Enabled = true;
			}
			else if (((ComboBox)sender).SelectedIndex > 1)
			{
				tb_c_source1.Enabled = true;
				tb_c_source2.Enabled = false;
			}
			else
			{
				tb_c_source1.Enabled = false;
				tb_c_source2.Enabled = false;
			}
		}

		#endregion











	}
}
